package com.lvliucun.validate.check.impl;

import com.alibaba.fastjson.JSONObject;
import com.lvliucun.validate.check.ParamChecker;
import com.lvliucun.validate.exception.CustomerErrorCodeEnum;
import com.lvliucun.validate.exception.ParamException;
import com.lvliucun.validate.utils.FiledNameSplitUtil;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * @version 1.0
 * @Description 参数校验器：多属性全部为空才失败，有一个非空即成功。字段之间用"&"分隔。
 * @Author:zhuojiajin
 * @Date 2020/8/15
 **/
@Component
public class ParamNotAllNull implements ParamChecker {

    @Override
    public boolean checkParam(JSONObject args, String filedName,String path) throws Exception {
        Integer falseNum = 0;
        Integer filedNum = 1;
        if(filedName.contains("&")){
            String[] filedNames = filedName.split("&");
            filedNum = filedNames.length;
            if(filedNames.length>1){
                for (String filed:filedNames) {
                    String[] filedStr = FiledNameSplitUtil.getFileName(filed);
                    Map<String,Object> value = FiledNameSplitUtil.getFiledValue(filedStr,args);
                    if(null == value || StringUtils.isEmpty(value.get("value"))){
                        falseNum +=1;
                    }
                }
            }else{
                String[] filedStr = FiledNameSplitUtil.getFileName(filedNames[0]);
                Map<String,Object> value = FiledNameSplitUtil.getFiledValue(filedStr,args);
                if(null == value || StringUtils.isEmpty(value.get("value"))){
                    falseNum +=1;
                }
            }
        }else{
            String[] filedStr = FiledNameSplitUtil.getFileName(filedName);
            Map<String,Object> value = FiledNameSplitUtil.getFiledValue(filedStr,args);
            if(null == value || StringUtils.isEmpty(value.get("value"))){
                falseNum +=1;
            }
        }
        if(falseNum == filedNum){
            throw new ParamException(CustomerErrorCodeEnum.PARAM_NOT_ALL_NULL,"参数",path);
        }
        return true;
    }
}

